package com.itwenke.springbootdemo.caffeine.controller;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping(path = {"api/cache"})
public class CacheController {

    @Cacheable(value = "say", cacheManager = "caffeineCacheManager", key = "'p_' + #name")
    @GetMapping(path = "say")
    public String sayHello(String name) {
        return "hello " + name + "-->" + UUID.randomUUID();
    }

    @Cacheable(value = "condition", cacheManager = "caffeineCacheManager", key = "#age", condition = "#age % 2 == 0")
    @GetMapping(path = "condition")
    public String setByCondition(Integer age) {
        return "condition: " + age + "-->" + UUID.randomUUID();
    }

    @Cacheable(value = "unless", cacheManager = "caffeineCacheManager", key = "#age", unless = "#age % 2 == 0")
    @GetMapping(path = "unless")
    public String setByUnless(Integer age) {
        return "unless: " + age + "-->" + UUID.randomUUID();
    }

    @CachePut(value = "say", cacheManager = "caffeineCacheManager", key = "'p_' + #name")
    @GetMapping(path = "cachePut")
    public String cachePut(String name) {
        return "hello " + name + "-->" + UUID.randomUUID();
    }

    @CacheEvict(value = "say", cacheManager = "caffeineCacheManager", key = "'p_' + #name")
    @GetMapping(path = "evict")
    public String evict(String name) {
        return "evict " + name + "-->" + UUID.randomUUID();
    }

    @Caching(cacheable = @Cacheable(value = "say", cacheManager = "caffeineCacheManager", key = "'p_' + #name")
            , evict = @CacheEvict(value = "condition", cacheManager = "caffeineCacheManager", key = "#age"))
    @GetMapping(path = "caching")
    public String caching(String name, Integer age) {
        return "caching " + name + "-->" + UUID.randomUUID();
    }

}
